#include "Scheduler.h"

//构造函数
Scheduler::Scheduler() {
    recordId = 0;
    serviceQueue = new ServiceQueue();
    waitQueue = new WaitQueue();
    copeThread();
}

Scheduler::Scheduler(int i) {
    recordId = 0;
    serviceQueue = new ServiceQueue();
    waitQueue = new WaitQueue();
}

void Scheduler::copeThread() {
    HANDLE handle1 = CreateThread(NULL, 0, LPTHREAD_START_ROUTINE(cope), NULL, 0, NULL);
    CloseHandle(handle1);
}

void Scheduler::cope() {
    Scheduler *sche = new Scheduler(1);
    time_t now = time(0);
    tm ltm;
    localtime_s(&ltm, &now);
    int secNow = ltm.tm_sec;
    int secJust = secNow - 1;
    while (1) {    
        if (secNow == secJust + 1) {
            secJust = secNow;
            sche->copeMessage();
        }
        now = time(0);
        localtime_s(&ltm, &now);
        secNow = ltm.tm_sec;
    }
}

void Scheduler::copeMessage() {
    //1.时间片检查
    for (vector<WaitObj>::iterator it = waitQueue->getMidWindQueue()->begin(); it != waitQueue->getMidWindQueue()->end(); it++) {
        int time = it->getWaitTime();
        if (time == 0) {
            WaitObj wait = *it;
            copeTimeOut(WindMood::HIGH, &wait);
        }
    }
    for (vector<WaitObj>::iterator it = waitQueue->getLowWindQueue()->begin(); it != waitQueue->getLowWindQueue()->end(); it++) {
        int time = it->getWaitTime();
        if (time == 0) {
            WaitObj wait = *it;
            copeTimeOut(WindMood::MEDIUM, &wait);
        }
    }
    for (vector<WaitObj>::iterator it = waitQueue->getHighWindQueue()->begin(); it != waitQueue->getHighWindQueue()->end(); it++) {
        int time = it->getWaitTime();
        if (time == 0) {
            WaitObj wait = *it;
            copeTimeOut(WindMood::LOW, &wait);
        }
    }
    //2.检查来自room数据库的信息
    std::vector<Json::Value> info = dbfacade->to_schedule_list;
    for (std::vector<Json::Value>::iterator it = info.begin(); it != info.end(); it++) {
        if ((*it)["queryType"] == (int)QueryType::WINDSTOP) {//收到来自roomBean的达到目标温度的json
            copeStopWindMessage(*it);
        }
        else if ((*it)["queryType"] == (int)QueryType::WINDSTART) {//收到来自roomBean的的超过目标温度1度的json
            copeWindAgainMessage(*it);
        }
    }
}

//处理时间片到期的等待对象
void Scheduler::copeTimeOut(WindMood wind, WaitObj* wait) {
    if (wind == WindMood::HIGH) {//可以进入服务队列
        if (serviceQueue->getHighWindQueue()->empty()) {//可以进入服务队列
            struct roomInfo room = getRoomInfo(wait->getRoomId());
            deleteQueue(QueueType::WAIT, wait, room, 0, WindMood::NONE);
            selectServiceToWait();
        }
    }
    else if (wind == WindMood::MEDIUM) {
        if (!(serviceQueue->getLowWindQueue()->empty() && serviceQueue->getLowWindQueue()->empty())) {//可以进入服务队列
            struct roomInfo room = getRoomInfo(wait->getRoomId());
            deleteQueue(QueueType::WAIT, wait, room, 0, WindMood::NONE);
            selectServiceToWait();
        }
    }
    else if (wind == WindMood::LOW) {
        if (!(serviceQueue->getLowWindQueue()->empty())) {//可以进入服务队列
            struct roomInfo room = getRoomInfo(wait->getRoomId());
            deleteQueue(QueueType::WAIT, wait, room, 0, WindMood::NONE);
            selectServiceToWait();
        }
    }
}

//接收来自通信对象的消息并进行处理：1.开关机  2.调整房间信息
void Scheduler::copeCommunicationMessage(Json::Value mainP) {
    //解包的固定项
    time_t time = mainP["time"].asInt();
    Type type = Type(mainP["type"].asInt());
    Identity source = Identity(mainP["source"].asInt());
    QueryType queryType = QueryType(mainP["queryType"].asInt());
    int roomId = mainP["roomId"].asInt();
    if (type == Type::QUERY) {
        struct roomInfo room = getRoomInfo(roomId);
        if (queryType == QueryType::CHANGEROOM) {//调整房间信息：调温/调风  
            double targetT = mainP["targetT"].asInt();
            WindMood targetW = WindMood(mainP["targetW"].asInt());
            if (targetT == 0) {//是调风请求             
                //1.记录操作record并插入对应数据库
                Record re = createMainpRecord(time, OptionType::CHANGEW, room, roomId, room.requestT, targetW);
                //2.查找对应对象并作有关队列的相应处理
                RequestObj reObjj = searchObj(roomId);
                RequestObj* reObj = &reObjj;
                if (reObjj.getRoomId() != -1) {//该对象在两个队列中
                    if (reObjj.getRequestType() == RequestType::SERVICEOBJ) {//在服务队列中
                        ServiceObj* ser = (ServiceObj*)reObj;
                        int serverNum = serviceQueue->getHighWindQueue()->size() + serviceQueue->getMidWindQueue()->size() + serviceQueue->getLowWindQueue()->size();
                        if (serverNum < MAXSERVER) {//直接调风即可
                            ser->setRequestW(targetW);
                        }
                        else {
                            //把该对象放入等待队列中
                            //(1)从服务队列中删除并创建相应的record
                            bool d = deleteQueue(QueueType::SERVICE, &reObjj, room, room.requestT, targetW);
                            if (d == false) {
                                std::cout << "error delete from serviceQueue" << std::endl;
                            }
                            //（3）创建等待对象并插入等待队列
                            WaitObj* waitNew = createAndInsertWait(&reObjj, targetW, room.requestT, room, roomId);
                            //(4)选取等待队列优先级最高的进入服务队列
                            selectWaitToService();
                        }
                    }
                    else if (reObjj.getRequestType() == RequestType::WAITOBJ) {//在等待队列中
                        WaitObj* wait = (WaitObj*)reObj;
                        //把该等待对象重新放入等待队列中
                        //（1）从等待队列中删除
                        bool d = deleteQueue(QueueType::WAIT, &reObjj, room, 0, WindMood::NONE);
                        if (d == false) {
                            std::cout << "error delete from serviceQueue" << std::endl;
                        }
                        //（2）创建新的等待对象放入等待队列中
                        WaitObj* waitNew = createAndInsertWait(&reObjj, targetW, room.requestT, room, room.roomId);
                        
                        //(3)选取等待队列优先级最高的进入服务队列
                        
                    }
                }
                else {//该对象不在两个队列中（已经达到了目标温度），代码部分不需要处理
                    ;
                }
                //3.发出调整房间信息的json给数据库……
                //调整房间风速targetW
                Json::Value changeRoom;
                changeRoom["time"] = time;
                changeRoom["type"] = (int)Type::QUERY;
                changeRoom["source"] = (int)source;
                changeRoom["queryType"] = (int)QueryType::CHANGEROOM;
                changeRoom["roomId"] = roomId;
                changeRoom["targetT"] = 0.0;
                changeRoom["targetW"] = (int)targetW;
                changeRoom["state"] = 0;
                dbfacade->RoomQuery(changeRoom);
            }
            else if (targetW == WindMood::NONE) {//是调温请求
                //1.记录操作record并插入对应数据库
                Record re = createMainpRecord(time, OptionType::CHANGET, room, roomId, targetT, room.nowW);              
                //2.查找对应对象并作有关队列的相应处理
                RequestObj reObjj = searchObj(roomId);
                RequestObj* reObj = &reObjj;
                if (reObjj.getRoomId() != NULL) {//该对象在这两个队列中
                    if (reObjj.getRequestType() == RequestType::SERVICEOBJ) {//在服务队列中
                        ServiceObj* ser = (ServiceObj*)reObj;
                        //(1)修改温度
                        ser->setRequestT(targetT);
                        //(2)查看是否达到了目标温度
                        if (targetT >= MIN_TEMPRATURE && targetT <= DEFAULT_TEMPRATURE) {//制冷模式
                            if (targetT >= room.nowT) {//达到目标温度
                                //从服务队列中删除
                                bool d = deleteQueue(QueueType::SERVICE, &reObjj, room, targetT, room.nowW);
                                if (d == false) {
                                    std::cout << "delete error from serviceQueue" << std::endl;
                                }
                                //选取等待对象进入服务队列
                                int waitNum = waitQueue->getHighWindQueue()->size() + waitQueue->getMidWindQueue()->size() + waitQueue->getLowWindQueue()->size();
                                if (waitNum > 0) {
                                    selectWaitToService();
                                }
                            }
                            else {//没有达到
                                //继续留在服务队列中，代码部分不做处理
                            }
                        }
                        else {
                            if (targetT <= room.nowT) {//达到目标温度
                                //从服务队列中删除
                                bool d = deleteQueue(QueueType::SERVICE, &reObjj, room, targetT, room.nowW);
                                if (d == false) {
                                    std::cout << "delete error from serviceQueue" << std::endl;
                                }
                                //选取等待对象进入服务队列
                                int waitNum = waitQueue->getHighWindQueue()->size() + waitQueue->getMidWindQueue()->size() + waitQueue->getLowWindQueue()->size();
                                if (waitNum > 0) {
                                    selectWaitToService();
                                }
                                
                            }
                            else {//没有达到
                                //继续留在服务队列中，代码部分不做处理
                            }
                        }
                    }
                    else if (reObjj.getRequestType() == RequestType::WAITOBJ) {//在等待队列中
                        WaitObj* wait = (WaitObj*)reObj;
                        //(1)修改温度
                        wait->setRequestT(targetT);
                        //(2)查看是否达到了目标温度
                        if (targetT >= MIN_TEMPRATURE && targetT <= DEFAULT_TEMPRATURE) {//制冷模式
                            if (targetT >= room.nowT) {//达到目标温度
                                //从等待队列中删除
                                bool d = deleteQueue(QueueType::WAIT, &reObjj, room, 0, WindMood::NONE);
                                if (d == false) {
                                    std::cout << "delete error from waitQueue" << std::endl;
                                }
                            }
                            else {//没有达到
                                //继续留在等待队列中，代码部分不做处理
                            }
                        }
                        else {//制热模式
                            if (targetT <= room.nowT) {//达到目标温度
                                //从等待队列中删除
                                bool d = deleteQueue(QueueType::WAIT, &reObjj, room, 0, WindMood::NONE);
                                if (d == false) {
                                    std::cout << "delete error from waitQueue" << std::endl;
                                }
                            }
                            else {//没有达到
                                //继续留在等待队列中，代码部分不做处理
                            }
                        }
                    }
                }
                else {//该对象不在两个队列中（已经达到了目标温度），
                    if (targetT >= MIN_TEMPRATURE && targetT <= DEFAULT_TEMPRATURE) {//制冷模式
                        if (targetT >= room.nowT) {//达到目标温度
                            //不做处理
                        }
                        else {//没有达到，需要重新为其创建等待对象/或服务对象
                            int serverNum = serviceQueue->getHighWindQueue()->size() + serviceQueue->getMidWindQueue()->size() + serviceQueue->getLowWindQueue()->size();
                            if (serverNum < MAXSERVER) {
                                ServiceObj* ser = createAndInsertService(NULL, room.nowW, targetT, room, room.roomId);
                            }
                            else {
                                WaitObj* wait = createAndInsertWait(NULL, room.nowW, targetT, room, room.roomId);
                            }
                            
                        }
                    }
                    else {//制热模式
                        if (targetT <= room.nowT) {//达到目标温度
                            //不做处理
                        }
                        else {//没有达到，需要重新为其创建等待对象
                            int serverNum = serviceQueue->getHighWindQueue()->size() + serviceQueue->getMidWindQueue()->size() + serviceQueue->getLowWindQueue()->size();
                            if (serverNum < MAXSERVER) {
                                ServiceObj* ser = createAndInsertService(NULL, room.nowW, targetT, room, room.roomId);
                            }
                            else {
                                WaitObj* wait = createAndInsertWait(NULL, room.nowW, targetT, room, room.roomId);
                            }                            
                        }
                    }
                }
                //3.发出调整房间信息的json给数据库……
                //调整房间目标温度targetT
                Json::Value changeRoom;
                changeRoom["time"] = time;
                changeRoom["type"] = (int)Type::QUERY;
                changeRoom["source"] = (int)source;
                changeRoom["queryType"] = (int)QueryType::CHANGEROOM;
                changeRoom["roomId"] = roomId;
                changeRoom["targetT"] = targetT;
                changeRoom["targetW"] = (int)WindMood::NONE;
                changeRoom["state"] = 0;
                dbfacade->RoomQuery(changeRoom);
            }
        }
        else if (queryType == QueryType::ONOFF) {//开关机
            if (room.roomId == -1 || room.power == 0) {//此时是关机，则执行开机操作
                //1.记录操作record并插入对应数据库
                Record re = createMainpRecord(time, OptionType::ON, room, roomId, 0, WindMood::NONE);  
                int serverNum = serviceQueue->getHighWindQueue()->size() + serviceQueue->getMidWindQueue()->size() + serviceQueue->getLowWindQueue()->size();
                //2.确定服务队列是否已满
                if (serverNum < MAXSERVER) {//为其创建服务对象并进入服务队列
                    ServiceObj* ser = createAndInsertService(NULL, room.nowW, room.requestT, room, roomId);
                }
                else {
                    //为其创建等待对象并进入等待队列
                    WaitObj* wait = createAndInsertWait(NULL, room.nowW, room.requestT, room, roomId);
                }               
                //3.发送开关机信息的query
                Json::Value onOrOff;
                onOrOff["time"] = time;
                onOrOff["type"] = (int)Type::QUERY;
                onOrOff["source"] = (int)source;
                onOrOff["queryType"] = (int)QueryType::ONOFF;
                onOrOff["roomId"] = roomId;
                dbfacade->RoomQuery(onOrOff);
            }
            else {//此时是开机，则执行关机操作
                //1.记录操作record并插入对应数据库
                Record re = createMainpRecord(time, OptionType::OFF, room, roomId, 0, WindMood::NONE);                
                //2.查找对应对象并作有关队列的相应处理
                RequestObj reObjj = searchObj(roomId);
                RequestObj* reObj = &reObjj;
                if (reObjj.getRoomId() != -1) {//在两个队列中
                    if (reObjj.getRequestType() == RequestType::SERVICEOBJ) {
                        int serverNum = serviceQueue->getHighWindQueue()->size() + serviceQueue->getMidWindQueue()->size() + serviceQueue->getLowWindQueue()->size();
                        ServiceObj* ser = (ServiceObj*)reObj;
                        //(1)从服务队列中删除并创建相应的record
                        bool d = deleteQueue(QueueType::SERVICE, &reObjj, room, room.requestT, room.nowW);
                        if (d == false) {
                            std::cout << "error delete from serviceQueue" << std::endl;
                        }                      
                        //(2)选取等待队列优先级最高的进入服务队列
                        int waitNum = waitQueue->getHighWindQueue()->size() + waitQueue->getMidWindQueue()->size() + waitQueue->getLowWindQueue()->size();
                        if (waitNum > 0) {
                            selectWaitToService();
                        }
                        
                    }
                    else if (reObjj.getRequestType() == RequestType::WAITOBJ) {
                        WaitObj* wait = (WaitObj*)reObj;
                        //从等待队列中删除
                        bool d = deleteQueue(QueueType::WAIT, &reObjj, room, 0, WindMood::NONE);
                        if (d == false) {
                            std::cout << "delete error from waitQueue" << std::endl;
                        }
                    }
                }
                else {//不在两个队列中
                    //不用操作
                }
                //3.发送开关机信息的query
                Json::Value onOrOff;
                onOrOff["time"] = time;
                onOrOff["type"] = (int)Type::QUERY;
                onOrOff["source"] = (int)source;
                onOrOff["queryType"] = (int)QueryType::ONOFF;
                onOrOff["roomId"] = roomId;
                dbfacade->RoomQuery(onOrOff);
            }
        }
        else {
            std::cout << "message received error" << std::endl;
        }
    }
}

//收到来自roomBean的达到目标温度的消息并处理
void Scheduler::copeStopWindMessage(Json::Value stopW) {
    //解包的固定项
    time_t time = stopW["time"].asInt();
    Type type = Type(stopW["type"].asInt());
    Identity source = Identity(stopW["source"].asInt());
    QueryType queryType = QueryType(stopW["queryType"].asInt());
    int roomId = stopW["roomId"].asInt();

    //进行处理，该room一定正在被服务
    RequestObj reObjj = searchObj(roomId);
    RequestObj* reObj = &reObjj;
    if (reObjj.getRequestType() == RequestType::SERVICEOBJ) {
        ServiceObj* ser = (ServiceObj*)reObj;
        struct roomInfo room = getRoomInfo(roomId);
        deleteQueue(QueueType::SERVICE, &reObjj, room, room.requestT, room.nowW);
    }
    else {
        std::cout << "stop wind obj is not in serviceQueue" << std::endl;
    }
}

//收到来自roomBean的的超过目标温度1度的json
void Scheduler::copeWindAgainMessage(Json::Value again) {
    //解包的固定项
    time_t time = again["time"].asInt();
    Type type = Type(again["type"].asInt());
    Identity source = Identity(again["source"].asInt());
    QueryType queryType = QueryType(again["queryType"].asInt());
    int roomId = again["roomId"].asInt();

    if (queryType == QueryType::WINDSTART) {
        struct roomInfo room = getRoomInfo(roomId);
        createAndInsertWait(NULL, room.nowW, room.requestT, room, room.roomId);
    }
}

//在等待队列和服务队列中查找room对应的对象
RequestObj Scheduler::searchObj(int roomId) {
    //1.在服务队列中查找
    ServiceObj ser = serviceQueue->search(roomId);
    if (ser.getRoomId() != -1) {//在服务队列中找到该对象
        return ser;
    }
    else {
        //2.在等待队列中查找
        WaitObj wait = waitQueue->search(roomId);
        if (wait.getRoomId() != -1) {//在等待队列中找到该对象
            return wait;
        }
        else {//两个队列中都没有找到该对象
            RequestObj re;
            re.setRoomId(-1);
            return re;
        }
    }
}

//获取房间信息
struct roomInfo Scheduler::getRoomInfo(int roomId) {
    //请求从roomBean中查找相关信息
    Json::Value getRoom;
    getRoom["time"] = time;
    getRoom["type"] = (int)Type::QUERY;
    getRoom["source"] = 0;
    getRoom["queryType"] = (int)QueryType::ROOM;
    getRoom["roomId"] = roomId;

    Json::Value roomGet = dbfacade->RoomResponse(getRoom);
    time_t time = roomGet["time"].asInt();
    Type type = Type(roomGet["type"].asInt());
    Identity source = Identity(roomGet["source"].asInt());
    QueryType queryType = QueryType(roomGet["queryType"].asInt());
    int roomI = roomGet["roomId"].asInt();
    double nowT = roomGet["nowT"].asDouble();
    double requestT = roomGet["requestT"].asDouble();
    WindMood nowW = WindMood(roomGet["nowW"].asInt());
    int power = roomGet["power"].asInt();

    //(3)建立结构体
    struct roomInfo room;
    room.roomId = roomI;
    room.nowT = nowT;
    room.requestT = requestT;
    room.nowW = nowW;
    room.power = power;
    return room;
}

//建立操作record并插入数据库
Record Scheduler::createMainpRecord(time_t time, OptionType option, struct roomInfo room, int roomId, int targetT, WindMood targetW) {
    //(1)新建record
    Record* re = new Record();
    re->setTime(time);
    re->setRoomId(roomId);
    re->setRecordId(recordId++);
    re->setRecordType(RecordType::USEROPERATION);
    re->setCurrentW(room.nowW);
    re->setCurrentT(room.nowT);
    re->setRequestW(targetW);
    re->setRequestT(targetT);
    re->setOptionType(option);
    re->setType(Type::QUERY);
    //(2)插入数据库
    dbfacade->insertRecord(re);
    std::cout << "record:," << re->getRecordId() <<" room:,"<<re->getRoomId()<<" USEROPERATION ";
    if (option == OptionType::ON) {
        std::cout << "ON " ;
    }
    else if (option == OptionType::OFF) {
        std::cout << "OFF " << std::endl;
    }
    else if (option == OptionType::CHANGET) {
        std::cout << "CHANGET " ;
    }
    else if (option == OptionType::CHANGEW) {
        std::cout << "CHANGEW " ;
    }
    else {
        std::cout << "error " ;
    }
    std::cout << "CurrentW:";
    if (room.nowW == WindMood::HIGH) {
        std::cout << "high ";
    }
    else if (room.nowW == WindMood::MEDIUM) {
        std::cout << "mid ";
    }
    else if (room.nowW == WindMood::LOW) {
        std::cout << "low ";
    }
    std::cout << "RequestW:";
    if (targetW == WindMood::HIGH) {
        std::cout << "high ";
    }
    else if (targetW == WindMood::MEDIUM) {
        std::cout << "mid ";
    }
    else if (targetW == WindMood::LOW) {
        std::cout << "low ";
    }
    std::cout << "CurrentT:" << room.nowT << " RequestT:" << targetT << endl;
    return *re;
}

//创建进出服务队列的record
Record Scheduler::createSerRecord(RecordType recordType, ServiceObj ser, time_t time, struct roomInfo room, int targetT, WindMood targetW, int roomId) {
    Record* re = new Record();
    re->setTime(time);
    re->setRoomId(roomId);
    re->setRecordId(ser.getServiceId());
    re->setRecordType(recordType);
    re->setCurrentW(room.nowW);
    re->setCurrentT(room.nowT);
    re->setRequestW(targetW);
    re->setRequestT(targetT);
    re->setType(Type::QUERY);
    //插入数据库
    dbfacade->insertRecord(re);
    std::cout << "record:" << re->getRecordId() << "room:" << re->getRoomId();
    if (recordType == RecordType::SERVICESTART) {
        std::cout << " SERVICESTART ";
    }
    else if (recordType == RecordType::SERVICEEND) {
        std::cout << " SERVICEEND ";
    }
    std::cout << "CurrentW:";
    if (room.nowW == WindMood::HIGH) {
        std::cout << "high ";
    }
    else if (room.nowW == WindMood::MEDIUM) {
        std::cout << "mid ";
    }
    else if (room.nowW == WindMood::LOW) {
        std::cout << "low ";
    }
    std::cout << "RequestW:";
    if (targetW == WindMood::HIGH) {
        std::cout << "high ";
    }
    else if (targetW == WindMood::MEDIUM) {
        std::cout << "mid ";
    }
    else if (targetW == WindMood::LOW) {
        std::cout << "low ";
    }
    std::cout << "CurrentT:" << room.nowT << " RequestT:" << targetT << endl;
    return *re;
}

//把对象从队列中删去，及后续record处理
bool Scheduler::deleteQueue(QueueType queueType, RequestObj* reObj, struct roomInfo room, int targetT, WindMood targetW) {
    ServiceObj* ser = (ServiceObj*)reObj;
    //（1）从服务队列中删除
    bool d = serviceQueue->deletee(*ser);
    if (d == false) {
        std::cout << "delete error from serviceQueue" << std::endl;
    }
    //(2)创建出服务队列的record
    Record reOut = createSerRecord(RecordType::SERVICEEND, *ser, getTime(), room, targetT, targetW, room.roomId);
    return true;

}

//把对象插入队列中，及后续record处理
bool Scheduler::insertQueue(QueueType queueType, RequestObj* reObj, struct roomInfo room, int targetT, WindMood targetW, int roomId) {
    if (queueType == QueueType::SERVICE) {
        ServiceObj* ser = (ServiceObj*)reObj;
        //(1)插入到服务队列中
        serviceQueue->insert(*ser);
        //(2)创建进服务队列的reocrd
        Record reIn = createSerRecord(RecordType::SERVICESTART, *ser, getTime(), room, targetT, targetW, roomId);      
        //(3)传递“服务中”的房间状态
        Json::Value changeRoom;
        changeRoom["time"] = time;
        changeRoom["type"] = (int)Type::QUERY;
        changeRoom["source"] = (int)Identity::NONE;
        changeRoom["queryType"] = (int)QueryType::CHANGEROOM;
        changeRoom["roomId"] = room.roomId;
        changeRoom["targetT"] = 0;
        changeRoom["targetW"] = (int)WindMood::NONE;
        changeRoom["state"] = (int)RoomState::SERVING;
        dbfacade->RoomQuery(changeRoom);
        return true;
    }
    else if (queueType == QueueType::WAIT) {
        WaitObj* wait = (WaitObj*)reObj;
        //（1）插入到等待队列中
        waitQueue->insert(*wait);
        //（2）传递“在等待”的房间状态
        Json::Value changeRoom;
        changeRoom["time"] = time;
        changeRoom["type"] = (int)Type::QUERY;
        changeRoom["source"] = (int)Identity::NONE;
        changeRoom["queryType"] = (int)QueryType::CHANGEROOM;
        changeRoom["roomId"] = room.roomId;
        changeRoom["targetT"] = 0;
        changeRoom["targetW"] = (int)WindMood::NONE;
        changeRoom["state"] = (int)RoomState::WAITING;
        dbfacade->RoomQuery(changeRoom);
        return true;
    }
    else {
        return false;
    }
}

WaitObj* Scheduler::createAndInsertWait(RequestObj* reObj, WindMood targetW, int targetT, struct roomInfo room, int roomId) {
    if (reObj == NULL) {//创建一个针对调温请求的等待对象
        WaitObj* wait = new WaitObj();
        wait->setRequestW(targetW);
        wait->setRequestT(targetT);
        wait->setRoomId(roomId);
        insertQueue(QueueType::WAIT, wait, room, 0, WindMood::NONE, roomId);
        return wait;
    }
    else {//创建已有对象的等待对象
        //(3.1)创建等待对象
        WaitObj* wait = new WaitObj(reObj);
        //(3.2)修改风速和温度
        wait->setRequestW(targetW);
        wait->setRequestT(targetT);
        //(3.3)插入等待队列
        insertQueue(QueueType::WAIT, wait, room, 0, WindMood::NONE, roomId);
        return wait;
    }
}

ServiceObj* Scheduler::createAndInsertService(RequestObj* reObj, WindMood targetW, int targetT, struct roomInfo room, int roomId) {
    if (reObj == NULL) {//创建一个针对调温请求的服务对象
        ServiceObj* ser = new ServiceObj();
        ser->setRequestW(targetW);
        ser->setRequestT(targetT);
        ser->setRoomId(roomId);
        ser->setServiceId(recordId++);
        insertQueue(QueueType::SERVICE, ser, room, targetT, targetW, roomId);
        return ser;
    }
    else {
        return NULL;
    }
}

//从等待队列中选取优先级最高的等待对象进入服务队列
void Scheduler::selectWaitToService() {
    //(4)选取等待队列优先级最高并为其创建服务对象
    WaitObj* waitPri = waitQueue->getHighestPriWaitObj();
    ServiceObj* serPri = new ServiceObj(waitPri, recordId++);
    //(5)获取这个房间的信息        
    struct roomInfo roomSerPri = getRoomInfo(serPri->roomId);
    //(6)插入服务队列
    insertQueue(QueueType::SERVICE, serPri, roomSerPri, roomSerPri.requestT, roomSerPri.nowW, roomSerPri.roomId);
}

//从服务队列中选取广义优先级最低的服务对象进入等待队列
void Scheduler::selectServiceToWait() {
    //(1)选取服务队列优先级最低的进入等待队列
    ServiceObj* serPri = serviceQueue->getLowestPriServiceObj();
    //(2)获取serPri房间对应的信息
    struct roomInfo roomSerPri = getRoomInfo(serPri->roomId);
    //（3）进入等待队列
    WaitObj* waitPri = new WaitObj(serPri);
    insertQueue(QueueType::WAIT, waitPri, roomSerPri, 0, WindMood::NONE, roomSerPri.roomId);
    //(4)把该服务对象从服务队列中删除
    deleteQueue(QueueType::SERVICE, serPri, roomSerPri, roomSerPri.requestT, roomSerPri.nowW);
}

time_t Scheduler::getTime() {
    return std::time(0);
}